﻿<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<PagedList<PaperSystem.Models.UserList>>" %>
<%@ Import Namespace="Webdiyer.WebControls.Mvc"%>
<%@ Import Namespace="PaperSystem.Models"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>管理用户</title>
    <link type="text/css" href="/Content/common.css" rel="Stylesheet" />
    <style type="text/css">
    body{overflow:auto;}
    .page_header{height:50px;background:#2e5b89;font-family:"Microsoft Yahei","宋体";}
    .page_inner{width:960px;margin:0 auto;}
    .logo_wrap{width:100px;height:40px;float:left;margin-top:5px;}
    .logo_blue{display:block;width:100%;height:100%;background:url(/Content/images/logo_blue_min.gif) no-repeat;text-indent:-9999px;}
    
    .user_info{float:right;height:20px;line-height:20px;margin-top:18px;font-size:14px;color:#fff;}
    .user_info a:link,
    .user_info a:visited{color:#fff;text-decoration:underline;}
    .user_info a:hover{text-decoration:none;}
    
    .page_container{width:960px;margin:10px auto 0;}
    
    .action_container{padding:10px;}
    .col_id, .col_name, .col_password, .col_role, .col_action{height:100%;text-align:center;}
    
    .btn_edit{display:none;}
    .hover .btn_edit{display:inline-block;}
    div.msg,
    div.errmsg{top:-35px;left:374px;}
    </style>
    <script type="text/javascript" src="/Scripts/jquery-1.9.0.min.js"></script>
</head>
<body id="body">
    <div class="page_header">
        <div class="page_inner">
            <h1 class="logo_wrap">
                <a href="/Admin/Management/" class="logo_blue" title="试题库系统"></a>
            </h1>
            <div class="user_info">
                <%if (ViewData["userName"] != null){ %>欢迎您，<%=ViewData["userName"]%>。<%} %>
                <a href="/Login/Logout/">退出</a>
            </div>
        </div>
    </div>
    
    <div class="page_container ">
    <form id="form1" class="bd">
        <div class="action_container bd_bottom clearfix">
            <div class="left">
                <a id="addButton" class="btn_gray btn_space" title="增加新教师/学生">添加</a><a id="deleteButton" class="btn_gray" title="删除列表中选中的行">删除</a>
            </div>
            <div class="right">
                <label>账号：</label><%=Html.TextBox("user") %>
                <label>身份：</label><%=Html.DropDownList("role", ViewData["Dropdownlist"] as SelectList, "全部") %>
                <a href="javascript:void(0);" onclick="document.getElementById('form1').submit();" class="btn_gray">查询</a>
            </div>
        </div>
        <div class="table_container">
            <table id="infoTable">
                <thead>
                    <tr>
                        <th class="col_id" width="20%">账号</th>
                        <th class="col_name" width="16%">姓名</th>
                        <th class="col_password" width="16%">密码</th>
                        <th class="col_role" width="14%">身份</th>
                        <th class="col_action" width="36%"></th>
                    </tr>
                </thead>
                <tbody>
                    <% foreach (var item in Model)
                       { %>
                        <tr class="<%=Html.DisplayFor(modelItem => item.id) %>">
                            <td class="col_id"><%=Html.DisplayFor(modelItem => item.id) %></td>
                            <td class="col_name"><%=Html.DisplayFor(modelItem => item.name) %></td>
                            <td class="col_password"><%=Html.DisplayFor(modelItem => item.password) %></td>
                            <td class="col_role"><%=Html.DisplayFor(modelItem => item.role)%></td>
                            <td class="col_action col_edit"><a class="btn_gray btn_edit">修改</a></td>
                            <td class="col_action col_save" style="display:none;"><a class="btn_blue btn_space btn_save">保存</a><a class="btn_gray btn_cancel">取消</a></td>
                        </tr>
                    <%} %>
                </tbody>
            </table>
            <table id="addTable" class="none">
                <tr>
                    <td class="col_id" width="20%"><%=Html.TextBox("addId") %></td>
                    <td class="col_name" width="16%"><%=Html.TextBox("addName") %></td>
                    <td class="col_password" width="16%"><%=Html.TextBox("addPassword") %></td>
                    <td class="col_role" width="14%"><%=Html.DropDownList("addRole", ViewData["Dropdownlist"] as SelectList) %></td>
                    <td class="col_action" width="36%"><a id="addInsert" class="btn_blue btn_space">添加</a><a id="addCancel" class="btn_gray">取消</a></td>
                </tr>
            </table>
            <%=Html.AjaxPager(Model, new PagerOptions() { PageIndexParameterName = "page", ShowMorePagerItems = false, AlwaysShowFirstLastPageNumber = true, ShowFirstLast = false,PrevPageText = "上一页", NextPageText = "下一页", CurrentPagerItemWrapperFormatString = "<span class=\"cur_page_wrap page_wrap\">{0}</span>", NumericPagerItemWrapperFormatString = "<span class=\"page_wrap\">{0}</span>", NavigationPagerItemWrapperFormatString = "<span class=\"page_nav\">{0}</span>", CssClass = "pages clearfix", SeparatorHtml = "" }, new AjaxOptions() { UpdateTargetId = "body" })%>
        </div>
    </form>
    </div>
    <script type="text/javascript" src="/Scripts/common.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            //只能同时修改一行所用的全局变量
            var isEditing = false;

            //保存每一行修改前的信息
            var oldData = [];

            //记录选中的行
            var markInfo = '';

            //添加账号按钮
            $('#addButton').bind('click', function() { $('#addTable').removeClass('none'); $('#addTable').find('input').first().focus(); });

            //添加-取消按钮
            $('#addCancel').bind('click', function() {
                $('#addTable').find('input').val('');
                $('#addTable').addClass('none');
            });

            //修改按钮
            $('.table_container').on('click', '.btn_edit', function(event) {
                //只能同时修改一行
                if (isEditing == true) {
                    return false;
                } else {
                    isEditing = true;
                }

                var tr = $(this).parent().parent('tr');

                switchmode(tr, "edit");

                return false;
            });

            //修改-确定按钮
            $('.table_container').on('click', '.btn_save', function() {
                var tr = $(this).parent().parent('tr');

                //判断数据是否空
                if (tr.find('.col_name input').val() == '' || tr.find('.col_password input').val() == '') {
                    //提示错误
                    message('更新失败（请检查更新的内容）', 'error', true, 5000);
                    //复原数据
                    tr.find('.col_name input').val(oldData[0]);
                    tr.find('.col_password input').val(oldData[1]);
                    return false;
                }


                //Ajax提交数据
                $.ajax({
                    type: 'post',
                    url: '/Admin/Update/',
                    data: 'id=' + tr.find('.col_id').text()
                    + '&name=' + tr.find('.col_name input').val()
                    + '&password=' + tr.find('.col_password input').val()
                    + '&role=' + tr.find('.col_role').text(),
                    dataType: 'text',
                    success: function(msg) {
                        switchmode(tr, "normal");
                        message(msg, 'success', true, 5000);
                    },
                    error: function() {
                    }
                });

                //每次修改一行的限制
                isEditing = false;

                return false;
            });


            //修改-取消按钮
            $('.table_container').on('click', '.btn_cancel', function() {
                //只能同时修改一行
                if (isEditing == true) {
                    isEditing = false;
                } else {
                    return false;
                }

                var tr = $(this).parent().parent('tr');

                //判断数据是否空
                if (tr.find('.col_name input').val() == '' || tr.find('.col_password input').val() == '') {
                    //复原数据
                    tr.find('.col_name input').val(oldData[0]);
                    tr.find('.col_password input').val(oldData[1]);
                }

                switchmode(tr, "normal");
                return false;
            });

            //添加-确定按钮
            $('#addInsert').on('click', function() {
                var tr = $(this).parent().parent('tr');
                var id_value = tr.find('.col_id input').val();
                var name_value = tr.find('.col_name input').val();
                var password_value = tr.find('.col_password input').val();
                var role_value = tr.find('.col_role select').val();

                //判断数据是否空
                if (id_value == '' || name_value == '' || password_value == '') {
                    message("请填写完整数据", 'error', true, 5000);
                    return false;
                }

                //判断id是否是纯数字
                if (!/\d+/.test(id_value)) {
                    message("账号必须是数字", 'error', true, 5000);
                    return false;
                }

                //用户名不能太长
                if (name_value.length > 5) {
                    message("用户名不能超过5个字", 'error', true, 5000);
                    return false;
                }

                //同角色的用户名不能重复
                var current_users = $('tr.' + id_value);
                if (current_users.length > 0 && current_users.find('.col_role').text().indexOf(role_value) > -1) {
                    message("该账号已经存在了", 'error', true, 5000);
                    return false;
                }

                //准备ajax
                var ajaxData = 'id=' + id_value
                          + '&name=' + name_value
                          + '&password=' + password_value
                          + '&role=' + role_value;

                //ajax提交
                $.ajax({
                    type: 'post',
                    url: '/Admin/Insert/',
                    data: ajaxData,
                    dataType: 'text',
                    success: function(msg) {

                        //清除输入框的内容
                        $('#addTable').find('input').val('');

                        //隐藏输入
                        $('#addTable').addClass('none');

                        if (msg.indexOf('失败') > 0) {
                            message(msg, 'error', true, 5000);
                        } else {
                            message(msg, 'success', true, 5000);
                            //插入新一行
                            $('#infoTable tbody').append(
                                '<tr>'
                                    + '<td class="col_id">' + id_value + '</td>'
                                    + '<td class="col_name">' + name_value + '</td>'
                                    + '<td class="col_password">' + password_value + '</td>'
                                    + '<td class="col_role">' + role_value + '</td>'
                                    + '<td class="col_action col_edit"><a class="btn_gray btn_edit">修改</a></td>'
                                    + '<td class="col_action col_save" style="display:none;"><a class="btn_gray btn_save">确定</a><a class="btn_gray btn_cancel">取消</a></td>'
                                + '</tr>'
                            );
                        }
                    },
                    error: function(msg) {
                    }
                });
                return false;
            });

            //点击每行选中该行
            var objTable = $('#infoTable');
            objTable.on('click', 'tr:gt(0)', function(event) {
                var that = $(this);
                var target = $(event.srcElement || event.target);
                //点击input 和 button 时不选中该行
                if (target.is('input') || target.is('a')) {
                    return;
                }
                if (that.hasClass('selected')) {
                    //如果原来已经选中，则点击后变为不选中，去掉class，并在table中去掉记录
                    that.removeClass('selected');
                    markTable(objTable, that.find('td.col_id'), that.find('td.col_role'), 'remove');
                } else {
                    //如果原来没选中，则点击后变为选中，加上class，并在table中加上记录，方便上传
                    that.addClass('selected');
                    markTable(objTable, that.find('td.col_id'), that.find('td.col_role'), 'add');
                }
            });

            //删除按钮
            $('#deleteButton').on('click', function(event) {
                if (markInfo == '') {
                    message('请先点击选择要删除的行', 'error', true, 5000);
                    return false;
                } else if (confirm('确认要删除选中的账号吗?')) {
                    //提交数据
                    $.ajax({ type: 'post',
                        url: '/Admin/Delete/',
                        data: 'deleteRows=' + markInfo,
                        dataType: 'text',
                        success: function(msg) {
                            //删除选中的行
                            $('#infoTable').find('tr.selected').remove();
                            message(msg, 'success', true, 5000);
                        },
                        error: function(msg) {
                            message(msg, 'error', true, 5000);
                        }
                    });
                }
            });

            //鼠标经过每一行时显示修改按钮
            objTable.on('mouseenter', 'tr:gt(0)', function(event) {
                if (!isEditing) {
                    $(this).addClass('hover');
                }
            }).on('mouseleave', 'tr:gt(0)', function(event) {
                $(this).removeClass('hover');
            });


            /*
            * 定义一些函数
            */

            //切换输入模式/正常模式
            //参数含义: tr: 该行的对象; mode: normal or edit
            function switchmode(tr, mode) {
                var array_col = ['col_name', 'col_password'];
                var td;
                if (mode == "normal") {
                    for (var i = 0; i < array_col.length; i++) {
                        td = tr.find('.' + array_col[i]);
                        td.html(td.find('input').val());
                    }
                    tr.find('.col_save').hide();
                    tr.find('.col_edit').show();
                } else if (mode == "edit") {
                    for (var i = 0; i < array_col.length; i++) {
                        td = tr.find('.' + array_col[i]);
                        //备份一下数据
                        oldData.push(td.text());
                        td.html('<input type="text" name="' + array_col[i] + '" value="' + td.text() + '" />');

                    }
                    tr.find('.col_edit').hide();
                    tr.find('.col_save').show();
                } else {
                    return false;
                }
            }

            //标记选中的行
            function markTable(objTable, idCol, roleCol, action) {
                var strOriginal = markInfo || '';
                var strRole = roleCol.text() == '学生' ? 's' : 't';
                var strToFind = strRole + idCol.text();
                var array;
                if (strOriginal == '') {
                    array = [];
                } else {
                    array = strOriginal.split(' ');
                }
                if (action == 'add') {
                    for (var i = 0; i < array.length; i++) {
                        if (array[i] == strToFind) {
                            return true;
                        }
                    }
                    array.push(strToFind);
                } else if (action == 'remove') {
                    for (var i = 0; i < array.length; i++) {
                        if (array[i] == strToFind) {
                            array.splice(i, 1);
                        }
                    }
                }
                markInfo = array.join(' ');
                return true;
            }
        });

        
    </script>
</body>
</html>
